package com.vallis.controller;


import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.fabric.xmlrpc.base.Array;
import com.vallis.model.Customer;
import com.vallis.service.CustomerService;
import com.vallis.util.DeleteFileUtil;
import com.vallis.util.TestImage;
import com.vallis.util.WaterMarkUtils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.ImageIcon;


@Controller
@RequestMapping("/")
public class CustomerController {
    @Autowired
    	private CustomerService customerService;
@RequestMapping("tologin")
    public String tologin(){
    	
    	return "login";
    }
@RequestMapping("index")
public String toindex(){
	
	return "index";
}


@RequestMapping("login")
public String login(String phone,String password,String sn,Model model,HttpSession session){
	System.out.println(phone);
	System.out.println(password);
	System.out.println(sn);
	String errormss=null;
	Customer thisc=null;
	try {
		thisc=customerService.login(phone);
	} catch (Exception e) {
		errormss="您的身份证号在系统中存在冲突！冲突原因为：字符错误！";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
	
	if (thisc.getSn().equals(sn)||thisc.getAgentlevel()==0) {
		

	//
if ((null!=thisc)&&(thisc.getPassword().equals(password))) {//判断是否正确
	if (thisc.getAgentlevel()==0) {//判断权限
		List<Customer> allCu=customerService.findAll();
		model.addAttribute("allCu", allCu);
		model.addAttribute("thisc", thisc);

session.setAttribute("User",thisc);
		return "admin";
	}
	List<Customer> allCu=customerService.findMyAfter(thisc.getId());
	model.addAttribute("thisc", thisc);
	model.addAttribute("allCu", allCu);
	
	model.addAttribute("myafter", allCu.size());

session.setAttribute("User",thisc);
	return showMypage(thisc.getId(),1, model);
}	
errormss="密码有误";
model.addAttribute("errormss", errormss);
return "fail";
	}
	errormss="授权码有误";
	model.addAttribute("errormss", errormss);
return "fail";
	
}
@RequestMapping("myafterPage")
public String showMypage(int thiscid, @RequestParam(value = "pn", defaultValue = "1") Integer pn,
		Model model){
Customer thisc=null;
	
	List<Customer> allCu=null;
	String errormss=null;
	try {
		thisc=customerService.selectByPrimaryKey(thiscid);
		allCu=customerService.findMyAfter(thisc.getId());
	} catch (Exception e) {
		errormss="密码有误";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
	
	PageHelper.startPage(pn, 10);
	
	PageInfo page = new PageInfo(allCu, 10);

	
	model.addAttribute("pageInfo", page);
	model.addAttribute("thisc", thisc);
	model.addAttribute("allCu", allCu);
	model.addAttribute("myafter", allCu.size());
	
	if (thisc.getAgentlevel()==0) {
		return "admin";
	}
	return "mypage";
}
@RequestMapping("about")
public String about(Model model){
	String contentxx="关于我们";
	model.addAttribute("contentxx", contentxx);
	return "about";
}

@RequestMapping("outLogin")
public String outLogin(HttpSession session){
//通过session.invalidata()方法来注销当前的session
session.invalidate();
return "login";
}
//添加代理
@RequestMapping("toAddCustomer")
public String toAddCustomer(int cid,Model model){
	System.out.println(cid);
	Customer c=null;
	String errormss=null;
	try {
		c=customerService.selectByPrimaryKey(cid);
	} catch (Exception e) {
		errormss="系统异常";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
	
	model.addAttribute("boss", c);
	return "addCustomer";
}
@RequestMapping("toUpdateCustomer")
public String toUpdateCustomer(int cid,Model model){
	System.out.println(cid);
	Customer c=customerService.selectByPrimaryKey(cid);
	model.addAttribute("thisCustomer", c);
	return "updateCustomer";
}
@RequestMapping("showCustomer")
public String showCustomer(int cid,Model model){
	System.out.println(cid);
	Customer c=customerService.selectByPrimaryKey(cid);
	model.addAttribute("thisCustomer", c);
	return "showCustomer";
}



@Test
public String calcSn(){
	String sn = "000000";
	for (int i = 0; i < 4; i++) {
		char c=(char)(int)(Math.random()*26+97);
		sn+=new Character(c).toString();
	}
	return sn;
}
@RequestMapping("toadmin")
public String toadmin(String phone,Model model,HttpSession session){
	Customer thisc=null;
	String errormss=null;
	List<Customer> allCu=new ArrayList<Customer>();
	try {
		thisc=customerService.login(phone);
		allCu=customerService.findAll();
	} catch (Exception e) {
		errormss="系统异常";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
	
	
	model.addAttribute("allCu", allCu);
	model.addAttribute("thisc", thisc);

session.setAttribute("User",thisc);
	return "admin";
	
	
}


@RequestMapping("addCustomer")
public String addCustomer(String name,	String phone,String weichat,String certnumber,String address,String agentlevel,String cashpledge,String methodofremittance,String bossname,String bossweichat,String boss,
		Model model){
	
	try {
		Customer test1	=customerService.findByCertNum(certnumber);
		Customer test2=	customerService.login(phone);
		
		if (test1!=null) {
			
			String errormss="身份证号存在重复！";
			model.addAttribute("errormss", errormss);
			return "fail";
		}
		if (test2!=null) {
			
			String errormss="手机号存在重复！";
			model.addAttribute("errormss", errormss);
			return "fail";
		}
	} catch (Exception e) {
		System.out.println(e);
		String errormss="身份证号或手机号存在重复！";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
	
	Customer c=new Customer();
	c.setAddress(address);
	c.setAgentlevel(Integer.parseInt(agentlevel));
	c.setBoss(Integer.parseInt(boss));
	c.setBossname(bossname);
	c.setBossweichat(bossweichat);
	c.setCertnumber(certnumber);
	c.setSn(calcSn());
	c.setPassword(certnumber.substring(12, 18));
	
	c.setMethodofremittance(Integer.parseInt(methodofremittance));
	c.setName(name);
	c.setPhone(phone);
	c.setWeichat(bossweichat);
	c.setCashpledge(Double.parseDouble(cashpledge));
	//c.setSn("sn");
	System.out.println(name);
	try {
		
		customerService.insertSelective(c);
	} catch (Exception e) {
		System.out.println(e);
		String errormss="添加失败";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
Customer thisc=customerService.selectByPrimaryKey(Integer.parseInt(boss));
	
	List<Customer> allCu=customerService.findMyAfter(thisc.getId());
	model.addAttribute("thisc", thisc);
	model.addAttribute("allCu", allCu);
	model.addAttribute("myafter", allCu.size());
	return showMypage(thisc.getId(), 1, model);
}

@RequestMapping("todeleteCustomer")
public String todeleteCustomer(String cid,String phone,Model model,HttpSession session,HttpServletRequest request){
	int cidd=Integer.parseInt(cid);
	Customer prodethiscustomer=customerService.selectByPrimaryKey(cidd);
	ServletContext sc = null;
	sc = request.getSession().getServletContext();
	 String srcImgPath=sc.getRealPath("/image/card.jpg") ; //源图片地址
	    String tarImgPath=sc.getRealPath("newimages/"+prodethiscustomer.getCertnumber()+".jpg"); //待存储的地址
	int prodethiscustomerLevel=0;
	try {
		prodethiscustomerLevel=prodethiscustomer.getAgentlevel();
	} catch (Exception e) {
		customerService.deleteByPrimaryKey(cidd);
		return toadmin(phone, model, session);
	}
	
	//Customer thisboss=customerService.selectByPrimaryKey(bossid);
	List<Customer> thisafter=customerService.findMyAfter(cidd);
	
	if (prodethiscustomerLevel==1) {
		for (Customer customer : thisafter) {
			customer.setBoss(0);
			customerService.updateByPrimaryKeySelective(customer);
		}
	}else if(prodethiscustomerLevel>=2){
		for (Customer customer : thisafter) {
			customer.setBoss(prodethiscustomer.getAgentlevel()-1);
			customerService.updateByPrimaryKeySelective(customer);
		}
		
	}if(prodethiscustomerLevel==0){
		String errormss="管理员不能被删除！！";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
	
	customerService.deleteByPrimaryKey(cidd);
	try {
		DeleteFileUtil.deleteFile(tarImgPath);
	} catch (Exception e) {
		// TODO: handle exception
	}
	
	return toadmin(phone, model, session);
}



@RequestMapping("showmypaper")
public String showmypaper(String thisid,Model model,HttpServletRequest request){
	System.out.println("id是："+thisid);
	ServletContext sc = null;
	sc = request.getSession().getServletContext();

	Customer c=customerService.selectByPrimaryKey(Integer.parseInt(thisid));
	 String srcImgPath=sc.getRealPath("/image/card.jpg") ; //源图片地址
	    String tarImgPath=sc.getRealPath("newimages/"+c.getCertnumber()+".jpg"); //待存储的地址
	  File file = new File(tarImgPath);
      if (!file.exists()) {
    	  String level="代理";
  		switch (c.getAgentlevel()) {
  		case 1:
  			level="总代";
  			break;
  	case 2:
  		level="一级";
  			break;
  	case 3:
  		level="二级";
  		break;
  	case 4:
  		level="三级";
  		break;
  	case 5:
  		level="四级";
  		break;
  		
  		}
  		Date date=new Date();
  		Calendar cal = Calendar.getInstance();
  		cal.setTime(date);//设置起时间
  		
  	cal.add(Calendar.YEAR, 1);//增加一年
  		
  		DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
  		df.format(date);
  		df.format(cal.getTime());
  		TestImage.createMark(srcImgPath, tarImgPath, c.getWeichat(), level, df.format(date)+"至"+df.format(cal.getTime()), c.getSn(), null, 1, "微软雅黑", 30, Color.BLACK);
  		String pathxx="newimages/"+c.getCertnumber()+".jpg";
  	    model.addAttribute("tarImgPath", pathxx);
  	    System.out.println("成功");
  	    return "mypaper";
      } else {
    	  String pathxx="newimages/"+c.getCertnumber()+".jpg";
		    model.addAttribute("tarImgPath", pathxx);
		    System.out.println("成功");
		    return "mypaper";
		  
      }
	
	
	
	
	
}

//更改信息
@RequestMapping("updateCustomer")
public String updateCustomer(String updateid,String name,	String phone,String weichat,String certnumber,String address,String agentlevel,String cashpledge,String methodofremittance,String bossname,String bossweichat,String boss,
		Model model){
	
	
	
	Customer c=new Customer();
	c.setId(Integer.parseInt(updateid));
	c.setAddress(address);
	c.setAgentlevel(Integer.parseInt(agentlevel));
	c.setBoss(Integer.parseInt(boss));
	c.setBossname(bossname);
	c.setBossweichat(bossweichat);
	c.setCertnumber(certnumber);
	c.setMethodofremittance(Integer.parseInt(methodofremittance));
	c.setName(name);
	c.setPhone(phone);
	c.setWeichat(bossweichat);
	c.setCashpledge(Double.parseDouble(cashpledge));
	//c.setSn("sn");
	System.out.println(name);
	try {
		customerService.updateByPrimaryKeySelective(c);
	} catch (Exception e) {
		String errormss="修改失败";
		model.addAttribute("errormss", errormss);
		return "fail";
	}
	List<Customer> allCu=customerService.findAll();
	model.addAttribute("allCu", allCu);
	return "admin";
}
}
